package com.hxexp.weixin.common.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

/**
 * HttpClient自定义响应处理器
 *
 * 将json结果转换成Java对象
 * @author li.jiang
 *
 * @param <T> Java对象类型
 */
public final class Json2ObjectHandler<T> implements ResponseHandler<T> {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private TypeReference<T> typeReference;

    /**
     * 响应处理器构造函数
     *
     * @param typeReference
     *            对象类型参数
     */
    public Json2ObjectHandler(TypeReference<T> typeReference) {
        this.typeReference = typeReference;
    }

    /**
     * 响应处理器构造函数
     *
     * @param typeReference
     *            对象类型参数
     * @param s
     *            属性命名策略
     */
    public Json2ObjectHandler(TypeReference<T> typeReference, PropertyNamingStrategy s) {
        this.typeReference = typeReference;
        objectMapper.setPropertyNamingStrategy(s);
    }
    @Override
    public T handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }

            return objectMapper.readValue(EntityUtils.toString(entity, "utf-8"), typeReference);
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    }

}
